package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.serve.dto.DeviceDto;
import com.zzyl.serve.vo.DeviceDetailVo;
import com.zzyl.serve.vo.DeviceReportDataVo;
import com.zzyl.serve.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备管理Service业务层处理
 *
 * @author liuyp
 * @date 2025-08-22
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client; //添加依赖加进来的

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备管理
     *
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备管理信息
     *
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return deviceMapper.deleteById(id);
    }

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //1.从物联网平台查询 所有的产品列表
        //ListProductsRequest: 华为云 IoTDA SDK 中用于查询产品列表的请求类
        ListProductsRequest requset = new ListProductsRequest();

        // 调用华为云IoTDA客户端，发送查询产品列表请求
        ListProductsResponse response = client.listProducts(requset);

        // 检查HTTP响应状态码，如果不是200表示请求失败
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口-同步产品列表失败");
        }

        //2.将产品列表缓存到Redis中
        // 从响应中   获取产品列表
        List<ProductSummary> products = response.getProducts();  //products官方文档里有解释
        // 将产品列表转换为JSON字符串并存储到Redis缓存中
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_KEY, JSONUtil.toJsonStr(products));

    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //1.从Redis中查询产品列表
        String str = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);

        //2.如果查不到就返回一个空集合
        if (StringUtils.isEmpty(str)) {
            return Collections.emptyList();
        }

        //3.将Redis中的json数组转换成vo列表返回
        return JSONUtil.toList(str, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //判断设备名称是否重复
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName());
        if (count(wrapper) > 0) {
            throw new BaseException("设备名称已存在，请重新输入");
        }
        //检验设备标识码是否重复
        wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId());
        Device device = getOne(wrapper);
        if (device != null) {
            throw new BaseException("设备标识码已存在");
        }
        //检验同一位置是否绑定了同一类产品
        wrapper = Wrappers.<Device>lambdaQuery()
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey());
        device = getOne(wrapper);
        if (device != null) {
            throw new BaseException("该位置/老人已绑定此设备");
        }

        //再去华为云iot注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice boby = new AddDevice();
        boby.setProductId(deviceDto.getProductKey());
        boby.setDeviceName(deviceDto.getDeviceName());
        boby.setNodeId(deviceDto.getNodeId());

        //准备设备的密钥
        AuthInfo authInfo = new AuthInfo();  //华为云规范密钥对象
        String string = UUID.randomUUID().toString(true); //通过UUID随机数设置
        authInfo.setSecret(string); //添加到规范密钥
        boby.setAuthInfo(authInfo);

        request.withBody(boby);
        //向华为云平台发请求，注册设备
        AddDeviceResponse response = client.addDevice(request); //addDevice是华为添加设备的规范
        //得到设备在互联网平台的id
        String iotId = response.getDeviceId();

        //设备保存数据库
        device = new Device();
        BeanUtils.copyProperties(deviceDto, device);
        device.setIotId(iotId);
        save(device);
    }

    /**
     * 查看设备上报的数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<DeviceReportDataVo> queryServiceProperties(String iotId) {
        //从华为云物联网上发请求，  获取设备的上报影子信息
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);  //通过request的iotid查询到设备影子

        List<DeviceShadowData> shadow = response.getShadow();
        if (shadow == null || shadow.isEmpty()) {
            return Collections.emptyList(); //如果查不到上传的数据，返回空集合
        }


        //获取上报的数据
        Map<String, Object> properties = (Map<String, Object>) shadow.get(0).getReported().getProperties();

        //获取上报的时间
        String eventTimestr = shadow.get(0).getReported().getEventTime();
        LocalDateTime reportTime = LocalDateTime.parse(eventTimestr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"));  //获取上报0时区
        LocalDateTime eventTime = reportTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();  //转换成东8区时间


        //封装结果
        ArrayList<DeviceReportDataVo> list = new ArrayList<>();
        properties.forEach((prop, value) -> {
            DeviceReportDataVo vo = new DeviceReportDataVo();
            vo.setFunctionId(prop);
            vo.setValue(value);
            vo.setEventTime(eventTime);
            list.add(vo);

        });
        return list;
    }

    /**
     * 查询设备详细信息
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo getInfo(String iotId) {
        //1先从数据库中查询设备数据

        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId, iotId);
        Device device = getOne(wrapper);
        if (device == null) {
            return null;
        }


        //2再从华为云IotDA中查询设备信息
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口华为云-查询设备信息失败");
        }


        //3封装vo
        DeviceDetailVo vo = new DeviceDetailVo();
        BeanUtils.copyProperties(device, vo);
        vo.setBindingLocation(Long.parseLong(device.getBindingLocation()));
        vo.setDeviceStatus(response.getStatus());

        String activeTimestr = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTimestr)) {
            LocalDateTime dateTime = LocalDateTime.parse(activeTimestr, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
            dateTime = dateTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            vo.setActiveTime(dateTime);
        }
        return vo;
    }

    /**
     * 查询设备的物模型属性
     *
     * @param productKey
     * @return
     */
    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("物联网-查询产品信息失败");
        }

        //response是华为云响应接收   ServiceCapabilities是响应回来的内部的集合列表
        return response.getServiceCapabilities();
    }


}
